<template>
  <el-dialog v-model="visible" title="会员标签">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" label-width="120px">
      <el-form-item label="用户名" prop="uname">
        <el-input v-model="dataForm.uname" disabled></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="flagIds">
        <el-checkbox v-model="item.checked" v-for="item in flagIds" :key="item.id" :label="item.name" size="default" border @change="flagChangeHandle($event, item.id)" />
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: "",
  uname: "",
  flagIds: [],
  status: 1
});

const rules = ref({});
const flagIds: any = ref([]);

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/member/flag/all").then((res) => {
    flagIds.value = res.data;
  });

  baseService.get("/member/member/" + id).then((res) => {
    let data = res.data;
    if (data.flagIds) {
      try {
        let flag = JSON.parse(data.flagIds);
        if (flag !== 0) {
          data.flagIds = flag;
          flagIds.value.map((item: any) => {
            if (data.flagIds.includes(item.id)) {
              item.checked = true;
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    }
    Object.assign(dataForm, data);
  });
};

const flagChangeHandle = (checked: any, id: any) => {
  let isChecked = checked;
  if (isChecked) {
    baseService.put("/member/flag/bind", { flagId: id, memberId: dataForm.id }).then(() => {
      ElMessage.success({
        message: "已加入该组",
        duration: 500
      });
      emit("refreshDataList");
    });
  } else {
    baseService.put("/member/flag/unbind", { flagId: id, memberId: dataForm.id }).then((result) => {
      ElMessage.success({
        message: "已移除该组",
        duration: 500
      });
      emit("refreshDataList");
    });
  }
};

defineExpose({
  init
});
</script>
